package com.example.start

import android.R.attr.data
import android.content.ActivityNotFoundException
import android.content.ContentValues
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.provider.BaseColumns
import android.util.Log
import android.view.ContextMenu
import android.view.ContextMenu.ContextMenuInfo
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.AdapterContextMenuInfo
import android.widget.Button
import android.widget.ListView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.fragment.app.DialogFragment
import androidx.preference.PreferenceManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.example.start.ui.theme.StartTheme
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import java.net.URL


class MainActivity : AppCompatActivity(), PolicyItemEditFragment.DialogClickListener {
    val dbHelper = FeedReaderContract.FeedReaderDbHelper(this)

    val list: MutableList<DataBean> = ArrayList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_layout)
        supportActionBar?.title = "主页"

        val preferences = PreferenceManager.getDefaultSharedPreferences(this).all
        try {
            var themeStr = preferences["list_preference_1"] as String
            when (themeStr)
            {
                "Light"->
                {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
                }
                "Dark"->
                {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
                }
                else->
                {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
                }
            }
        }
        catch (e : Exception)
        {

        }

        // 设置按钮点击事件监听器

        findViewById<ListView>(R.id.mainListView).onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
            val policyItem : PolicyItem = parent.getItemAtPosition(position) as PolicyItem
            openUrl(policyItem.url.toString())
        }
        var headView = LayoutInflater.from(this).inflate(R.layout.main_head_view, null, false)

        headView.findViewById<Button>(R.id.button3).setOnClickListener { // 创建一个Intent对象，用于启动下一个Activity
            val intent = Intent(this@MainActivity, WebActivity::class.java)
            // 启动下一个Activity
            startActivity(intent)
        }

        // 设置按钮点击事件监听器
        headView.findViewById<Button>(R.id.removeAllButton).setOnClickListener { // 创建一个Intent对象，用于启动下一个Activity
            val db = dbHelper.writableDatabase
            // Define 'where' part of query.
            val deletedRows = db.execSQL("DELETE FROM ${FeedReaderContract.FeedEntry.TABLE_NAME}")

            refreshList();
        }
        // 设置按钮点击事件监听器
        headView.findViewById<Button>(R.id.readDatabaseButton).setOnClickListener { // 创建一个Intent对象，用于启动下一个Activity
            refreshList()
        }
        headView.findViewById<Button>(R.id.openWatermarkButton).setOnClickListener { // 创建一个Intent对象，用于启动下一个Activity
            val intent = Intent(this@MainActivity, WatermarkActivity::class.java)
            // 启动下一个Activity
            startActivity(intent)
        }
        var swipeRefreshLayout = findViewById<SwipeRefreshLayout>(R.id.mainSwipeRefreshLayout)
        swipeRefreshLayout.setOnRefreshListener(OnRefreshListener {
            //创建线程，在子线程更新数据
            fetchNews()
        })

        findViewById<ListView>(R.id.mainListView).addHeaderView(headView)
        registerForContextMenu(findViewById<ListView>(R.id.mainListView))
        addImages()
        refreshList();

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main,menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId)
        {
            R.id.open_gov_website_item -> {
                openUrl("https://www.gov.cn/")
            }
            R.id.settings_item -> {
                val intent = Intent(this@MainActivity, SettingsActivity::class.java)
                // 启动下一个Activity
                startActivity(intent)
            }
        }
        return true
    }
    lateinit var selectedItem : PolicyItem
    override fun onCreateContextMenu(menu: ContextMenu, v: View?, menuInfo: ContextMenuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo)
        val info = menuInfo as AdapterContextMenuInfo
        selectedItem = findViewById<ListView>(R.id.mainListView).getItemAtPosition(info.position) as PolicyItem
        //Toast.makeText(applicationContext, "you choose the file : ", Toast.LENGTH_SHORT).show()
        menu.add(0, 0, 0, "删除")
        menu.add(0, 1, 0, "编辑")
        menu.add(0, 2, 0, "分享")
        menu.add(0, 3, 0, "通过蓝牙发送")
    }

    //方法1对应
    override fun onContextItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            0 -> {

                // Gets the data repository in write mode
                val db = dbHelper.writableDatabase
                // Define 'where' part of query.
                val selection = "${BaseColumns._ID} = ?"
                // Specify arguments in placeholder order.
                val selectionArgs = arrayOf(selectedItem.id.toString())
                // Issue SQL statement.
                val deletedRows = db.delete(FeedReaderContract.FeedEntry.TABLE_NAME, selection, selectionArgs)
                refreshList()
            }

            1 -> {
                val args = Bundle().apply {
                    putInt("data1",selectedItem.id as Int)
                    putString("data2", selectedItem.title)
                    putString("data3", selectedItem.url)
                }
                val dialogFragment = PolicyItemEditFragment()
                dialogFragment.arguments = args
                dialogFragment.setDialogClickListener(this)
                dialogFragment.show(supportFragmentManager, "CustomDialogFragment")
            }

            2 -> {
                val sendIntent = Intent()
                sendIntent.setAction(Intent.ACTION_SEND)
                sendIntent.putExtra(Intent.EXTRA_TEXT, "${selectedItem.title}\t${selectedItem.url}")
                sendIntent.setType("text/plain")
                val chooser = Intent.createChooser(sendIntent, "title")
                if (sendIntent.resolveActivity(packageManager) != null) {
                    startActivity(chooser)
                }
            }
            3 -> {
                val sendIntent = Intent()
                sendIntent.action = Intent.ACTION_SEND
                sendIntent.putExtra(Intent.EXTRA_TEXT, "${selectedItem.title}\t${selectedItem.url}")
                sendIntent.type = "text/plain"
                // 显式指定使用蓝牙来发送
                sendIntent.setPackage("com.android.bluetooth")

                try {
                    startActivity(sendIntent)
                } catch (e: ActivityNotFoundException) {
                    Toast.makeText(this, "Bluetooth not supported or no app found to perform this action", Toast.LENGTH_SHORT).show()
                }
            }

        }
        return true
    }
    // 实现 DialogClickListener 接口的方法
    override fun onDialogPositiveClick(dialog: DialogFragment, text1: String, text2: String) {
        // 对话框中点击了 "OK" 按钮的处理逻辑
        var d = dialog as PolicyItemEditFragment
        val db = dbHelper.writableDatabase

        val values = ContentValues().apply {
            put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, text1)
            put(FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE, text2)
        }

        val selection = "${BaseColumns._ID} = ?"
        val selectionArgs = arrayOf(d.data1.toString())
        val count = db.update(
            FeedReaderContract.FeedEntry.TABLE_NAME,
            values,
            selection,
            selectionArgs)

        Log.d("MainActivity", "EditText 1: $text1, EditText 2: $text2")
        // 这里可以处理输入的数据，例如保存到数据库或者进行其他操作
        refreshList();
    }

    override fun onDialogNegativeClick(dialog: DialogFragment) {
        // 对话框中点击了 "Cancel" 按钮的处理逻辑
        Log.d("MainActivity", "Dialog cancelled")
    }
    fun addImages()
    {
        fetchNews()
    }

    override fun onResume() {
        super.onResume()
        refreshList();
    }
    fun openUrl(url:String)
    {
        var intent = Intent(this,PolicyPreviewActivity::class.java)
        intent.putExtra("url",url)
        startActivity(intent)
    }
    fun addPolicyItemTest()
    {
        // Gets the data repository in write mode
        val db = dbHelper.writableDatabase
        // Create a new map of values, where column names are the keys
        val values = ContentValues().apply {
            put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, "123")
            put(FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE, "343")
        }
        // Insert the new row, returning the primary key value of the new row
        val newRowId = db?.insert(FeedReaderContract.FeedEntry.TABLE_NAME, null, values)
    }
    fun refreshList()
    {
        // Gets the data repository in write mode
        val db = dbHelper.writableDatabase
        val projection = arrayOf(BaseColumns._ID, FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE)

        val sortOrder = "${FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE} DESC"

        val cursor = db.query(
            FeedReaderContract.FeedEntry.TABLE_NAME,   // The table to query
            projection,             // The array of columns to return (pass null to get all)
            null,              // The columns for the WHERE clause
            null,          // The values for the WHERE clause
            null,                   // don't group the rows
            null,                   // don't filter by row groups
            sortOrder               // The sort order
        )
        val items = ArrayList<PolicyItem>()
        with(cursor) {
            while (moveToNext()) {
                val item = PolicyItem()
                item.id = getInt(getColumnIndexOrThrow(BaseColumns._ID))
                item.title = getString(getColumnIndexOrThrow("title"))
                item.url = getString(getColumnIndexOrThrow("link"))
                items.add(item)
            }
        }
        cursor.close()
        val dataList = ArrayList<String>()
        items.forEach { item ->
            dataList.add(item.title+item.url)
        }
        // 适配器
        var adapter = PolicyItemAdapter(items,this);

        // 设置适配器
        findViewById<ListView>(R.id.mainListView).setAdapter(adapter)

    }

    suspend fun getHtmlContent(urlString: String): String {
        return try {
            val url = URL(urlString)
            val connection = url.openConnection()
            connection.connect()

            // 读取网络响应
            val inputStream = connection.getInputStream()
            val content = inputStream.bufferedReader().use { it.readText() }
            content
        } catch (e: Exception) {
            // 处理异常
            e.printStackTrace()
            ""
        }
    }


    fun addPolicyItem(title : String, url : String)
    {
        // Gets the data repository in write mode
        val db = dbHelper.writableDatabase
        // Create a new map of values, where column names are the keys
        val values = ContentValues().apply {
            put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, title)
            put(FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE, url)
        }
        // Insert the new row, returning the primary key value of the new row
        val newRowId = db?.insert(FeedReaderContract.FeedEntry.TABLE_NAME, null, values)
    }
    fun fetchNews()
    {
        GlobalScope.launch {
            // 创建一个新的后台线程
            val html = withContext(Dispatchers.IO) {
                // 在IO线程中执行网络请求
                getHtmlContent("https://www.gov.cn/")
            }
            // 网页HTML内容获取成功后，在主线程中进行处理
            list.clear()
            var document = Jsoup.parse(html)
            // 在这里处理 HTML 内容
            var slides = document.getElementsByClass("news")[0]
            var imgs = slides.select("img")
            for (img in imgs) {
                var urlAddress = img.attribute("src").value
                urlAddress = urlAddress.replace("./","https://www.gov.cn/")
                var data = DataBean(urlAddress,"",2)
                list.add(data)
            }
            list.add(DataBean("https://s2.loli.net/2024/04/26/zrBFPflLXnjVKy5.png","",2))
            runOnUiThread {
                findViewById<SwipeRefreshLayout>(R.id.mainSwipeRefreshLayout).isRefreshing = false
                var banner:Banner<DataBean,BannerImageAdapter<DataBean>> = findViewById(R.id.banner)

                banner.setAdapter(object : BannerImageAdapter<DataBean>(list) {
                    override fun onBindView(holder: BannerImageHolder, data: DataBean, position: Int, size: Int) {
                        //图片加载自己实现
                        Glide.with(holder.itemView)
                            .load(data.imageUrl)
                            .apply(RequestOptions.bitmapTransform(RoundedCorners(30)))
                            .into(holder.imageView) }
                }).addBannerLifecycleObserver(this@MainActivity).setIndicator(CircleIndicator(this@MainActivity))
                banner.setOnBannerListener { data: Any, position: Int ->
                    when(position)
                    {
                        0->{
                            //openUrl("https://www.gov.cn/yaowen/liebiao/202404/content_6947433.htm")
                        }
                        1->{
                            //openUrl("https://www.gov.cn/yaowen/liebiao/202404/content_6947628.htm")
                        }
                        2->{
                            //openUrl("https://www.gov.cn/yaowen/tupian/202404/content_6947549.htm#12")
                        }
                        3->{
                            val intent = Intent(this@MainActivity, NationalInformationActivity::class.java)
                            // 启动下一个Activity
                            startActivity(intent)
                        }
                        4->{

                        }
                    }
                    //Toast.makeText(applicationContext, position.toString(), Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    StartTheme {
        Greeting("Android")
    }
}